<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2019/1/25
 * Time: 13:58
 */

namespace app\modules\serviceLocator;


class ServiceLocator
{
    private $_services = [];

    private $_instantiated = [];

    private $_shared = [];

    public function addInstance(string $class, $service, bool $share = true)
    {
        $this->_services[$class] = $service;
        $this->_instantiated[$class] = $service;
        $this->_shared[$class] = $share;
    }

    public function addClass(string $class, array $params, bool $share = true)
    {
        $this->_services[$class] = $params;
        $this->_shared[$class] = $share;
    }

    public function has(string $interface): bool
    {

    }

    public function get(string $class)
    {
        if (isset($this->_instantiated[$class]) && isset($this->_shared[$class])) {
            return $this->_instantiated[$class];
        }

        $args = $this->_services[$class];

        switch (count($args)) {
            case 0:
                $object = new $class();
                break;
            case 1:
                $object = new $class($args[0]);
                break;
            case 2:
                $object = new $class($args[0], $args[1]);
                break;
            case 3:
                $object = new $class($args[0], $args[1], $args[2]);
                break;
            default:
                throw new \OutOfRangeException('Too many arguments given');
        }

        if ($this->_shared[$class]) {
            $this->_instantiated[$class] = $object;
        }

        return $object;
    }
}